package service

import (
	"egin/app/models"
	"egin/app/responses"
	"egin/pkg/database"
	"egin/pkg/redigo"
	"encoding/json"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/gomodule/redigo/redis"
	"gorm.io/gorm"
)

func GetNavs(c *gin.Context) []*responses.PermissionMenuTree {

	session := sessions.Default(c)
	uid := session.Get("id")

	conn := redigo.GetPool().Get()
	defer conn.Close()

	getjson, err := redis.Bytes(conn.Do("hget", "admin_menu", uid))
	if err == nil {
		if len(getjson) > 0 {
			var getmenu []*responses.PermissionMenuTree
			err := json.Unmarshal(getjson, &getmenu)
			if err == nil {
				return getmenu
			}

		}
	}

	var list *models.Member
	database.Db().Preload("Role", func(db *gorm.DB) *gorm.DB {
		return db.Select("id").Preload("Permission", func(db *gorm.DB) *gorm.DB {
			return db.Select("id")
		})
	}).Where("id = ?", uid).Find(&list)

	var lists []uint
	for _, v := range list.Role {
		for _, y := range v.Permission {
			lists = append(lists, y.ID)
		}
	}

	if len(lists) == 0 {
		return nil
	}
	var menuList []models.Permission
	database.Db().Where(lists).Where("is_menu = 1").Order("sort asc").Find(&menuList)

	menu := buildMenuChild(0, menuList)
	json, _ := json.Marshal(menu)
	conn.Do("hset", "admin_menu", uid, json)

	return menu
}

//递归获取子菜单
func buildMenuChild(pid int, menuList []models.Permission) []*responses.PermissionMenuTree {
	var treeList []*responses.PermissionMenuTree
	for _, v := range menuList {
		if pid == v.PID {
			node := &responses.PermissionMenuTree{
				Id:         int(v.ID),
				Title:      v.Title,
				Icon:       v.Icon,
				Href:       v.Href,
				FontFamily: v.FontFamily,
				Pid:        v.PID,
			}
			child := buildMenuChild(int(v.ID), menuList)
			if len(child) != 0 {
				node.Children = child
			}
			// todo 后续此处加上用户的权限判断
			treeList = append(treeList, node)
		}
	}
	return treeList
}
